package com.example.myapplication3.document;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;

import com.example.myapplication3.document.bean.DocumentItem;
import com.example.myapplication3.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DocumentQueryHelper {
    private static final String TAG = "DocumentQueryHelper";
    private static final ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void asynLoadAllDocuments(Context context, int pageIndex, int itemCount, DocumentLoadCallback callback) {
        executor.execute(() -> {
            List<DocumentItem> documents = new ArrayList<>();

            String[] projection = {
                    MediaStore.Files.FileColumns._ID,
                    MediaStore.Files.FileColumns.DISPLAY_NAME,
                    MediaStore.Files.FileColumns.DATA,
                    MediaStore.Files.FileColumns.SIZE,
                    MediaStore.Files.FileColumns.DATE_ADDED,
                    MediaStore.Files.FileColumns.DATE_MODIFIED,
                    MediaStore.Files.FileColumns.MIME_TYPE
            };

            // 查询非媒体文件
            String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                    + MediaStore.Files.FileColumns.MEDIA_TYPE_NONE;

            String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
            Uri mediaUri = MediaStore.Files.getContentUri("external");

            try (Cursor cursor = context.getContentResolver().query(
                    mediaUri,
                    projection,
                    selection,
                    null,
                    sortOrder
            )) {
                if (cursor != null) {
                    cursor.moveToPosition(pageIndex * itemCount);
                    while (cursor.moveToNext()) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID));
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME));
                        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
                        long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE));
                        long dateAdded = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED));
                        long dateModified = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED));
                        String mime = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE));

                        // 如果MIME类型为空，尝试从文件名推断
                        if (mime == null || mime.isEmpty()) {
                            String extension = MimeTypeMap.getFileExtensionFromUrl(path);
                            mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                        }

                        Uri uri = ContentUris.withAppendedId(MediaStore.Files.getContentUri("external"), id);
                        String extension = path.substring(path.lastIndexOf(".") + 1).toLowerCase();

                        DocumentItem item = new DocumentItem(id, name, path, uri,
                                size, dateAdded, dateModified, mime, extension);
                        documents.add(item);

                        if (documents.size() >= itemCount) break;
                    }
                }
            } catch (Exception e) {
                LogUtils.e(TAG, "获取文档失败", e);
                callback.onDocumentsLoaded(null);
                return;
            }

            callback.onDocumentsLoaded(documents);
        });
    }

    public interface DocumentLoadCallback {
        void onDocumentsLoaded(List<DocumentItem> documents);
    }
}